﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NewsCrawler.Common.Models;
using System.Xml.Linq;
using HtmlAgilityPack;
using System.Net;
using System.IO;
using CrawlerManager;

namespace Chip
{
    internal class ChipArticle : BaseArticle
    {
        protected override string Folder
        {
            get { return "Chip"; }
        }

        public override void Parse()
        {
            WebClient client = new WebClient();
            string filePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
            client.DownloadFile(this.Url, filePath);
            
            HtmlDocument doc = new HtmlDocument();
            doc.Load(filePath);

            //HtmlNode altcsol = doc.DocumentNode.SelectSingleNode("/html[1]/body[1]/div[2]/div[5]/div[1]");
            //HtmlNode tarih = altcsol.SelectSingleNode("//div[20]/table[1]/tr[2]/td[1]/span[1]");
            HtmlNode tarih = doc.DocumentNode.SelectSingleNode("//div[@class='tarih']");
            HtmlNode article = doc.DocumentNode.SelectSingleNode("//div[@id='contextual']");
            HtmlNode nofollow = article.SelectSingleNode("a[@rel='nofollow']");
            HtmlNode image =
                doc.DocumentNode.SelectSingleNode("//div[@class='content_image_image']").SelectSingleNode("img");

            this.Images.Add(GetImagePath(image, client));
            if (nofollow != null)
            {
                this.Content = article.InnerHtml.Replace(nofollow.OuterHtml, string.Empty);
            }
            this.PublishDate = ParseTarih(tarih.InnerHtml);
            this.CultureCode = "tr-TR";
            //Console.WriteLine(tarih.InnerHtml);
        }

        private string GetImagePath(HtmlNode image, WebClient client)
        {
            string value = image.Attributes["src"].Value;
            string fileName = Path.Combine(GetImagePath(), Path.GetFileName(value));
            client.DownloadFile("http://www.chip.com.tr" + value, fileName);
            return fileName;
        }

        private DateTime ParseTarih(string innerHtml)
        {
            DateTime date = new DateTime();
            string[] parsed = innerHtml.Replace(" ", "").Split(',');
            if(parsed[0] == "Bugün")
            {
                date = CrawlerHelper.CopyDateTime(date, DateTime.Today, new int[]{}, true);
                DateTime saat = DateTime.Parse(parsed[1]);
                date = CrawlerHelper.CopyDateTime(saat, date, new int[] {2, 3}, false);
            }
            else
            {
                date = DateTime.Parse(innerHtml);
            }
            

            return date;
        }
    }
}
